﻿//*********************************************************************
//
//  文件名：ShortMessageService
//
//  作者： LW
//
//  作用：
//
//  日期：2015/9/28 10:26:36
//
//*********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YouTravel.DomainModels;
using YouTravel.QueryModels;
using YouTravel.ViewModels;
using Framework.Common.Exceptions;
using YouTravel.Framework.ResourceMessage;
using EntityFramework.Data.Core;
using IRepositories.Core;

namespace YouTravel.DomainService
{
    /// <summary>
    /// ShortMessageService
    /// 短信
    /// </summary>
    public class ShortMessageService : IShortMessageService
    {
        readonly IEFRepository<ShortMessage> _shortMessageRepository;
        public ShortMessageService(IUnitOfWork db, IEFRepository<ShortMessage> shortMessageRepository)
        {
            this._shortMessageRepository = shortMessageRepository;
            this._shortMessageRepository.SetDbContext(db);
        }

        /// <summary>
        /// 添加短信记录
        /// </summary>
        /// <param name="model"></param>
        public void SendMsg(ShortMessage model)
        {
            #region validate
            if (string.IsNullOrWhiteSpace(model.Receive))
                throw new DataValidationException(string.Format(BusinessResourceMessage.PleaseInput, "接收手机号"));
            if (string.IsNullOrWhiteSpace(model.Content))
                throw new DataValidationException(string.Format(BusinessResourceMessage.PleaseInput, "短信内容"));
            #endregion

            model.SendTime = DateTime.Now;

            this._shortMessageRepository.Insert(model);
        }

        /// <summary>
        /// 验证验证码有效性
        /// </summary>
        /// <param name="vcode">验证码</param>
        /// <param name="validDate">当前时间-有效分钟数</param>
        /// <returns></returns>
        public bool ValidateVCode(string vcode, DateTime validDate)
        {
            if (string.IsNullOrWhiteSpace(vcode))
                throw new DataValidationException(string.Format(BusinessResourceMessage.PleaseInput, "验证码"));

            var single = this._shortMessageRepository.Find(c => c.Code == vcode && c.SendTime >= validDate);
            if (single == null)
                return false;
            return true;
        }
    }
}
